﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using SlamCms.Common;
using SlamCms.SharePointServices.Authentication;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.Net;

namespace SlamCms.SharePointServices
{
	public static class AuthenticationService
	{
		public static ServiceResponse<HttpCookie> Login(string siteUrl, string username, string password)
		{

            var client = ServiceClients.GetAuthenticationServiceClient(siteUrl);

            ServiceResponse<HttpCookie> serviceResponse = new ServiceResponse<HttpCookie>();

            using (new OperationContextScope(client.InnerChannel))
            {
                LoginResult loginresponse = client.Login(username, password);

                HttpResponseMessageProperty response = (HttpResponseMessageProperty)
                 OperationContext.Current.IncomingMessageProperties[HttpResponseMessageProperty.Name];

               string[] attributes = response.Headers["Set-Cookie"].Split(';');

               HttpCookie cookie = new HttpCookie(loginresponse.CookieName);

                foreach (string attribute in attributes)
                {
                    if (attribute.Contains(loginresponse.CookieName))
                        cookie.Value = attribute.Replace(loginresponse.CookieName + "=", "");
                    if (attribute.Contains("expires"))
                        cookie.Expires = DateTime.Parse(attribute.Replace("expires=", "")).AddYears(1);
                    if (attribute.Contains("path"))
                        cookie.Path = attribute.Replace("path=", "");
                    if (attribute.Contains("HttpOnly"))
                        cookie.HttpOnly = true;
                }

                serviceResponse.Response = cookie;
            }

		    return serviceResponse;
		}
	}
}
